﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using OpenWaves.EPiServer.Comments.Content.DataMappers;
using OpenWaves.EPiServer.Comments.Content.Repositories;
using OpenWaves.EPiServer.Comments.Models.Requests;
using OpenWaves.EPiServer.Comments.Models.ValueObjects;

namespace OpenWaves.EPiServer.Comments.Controllers
{
    public class CommentsController : Controller
    {
        [HttpGet]
        public JsonResult GetComments(Guid parentContentGuid)
        {
            var commentsRepository = ServiceLocator.Resolve<ICommentsRepository>();

            return Json(commentsRepository.GetCommentsByParentContentGuid(parentContentGuid),
                        JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult AddComment(AddCommentRequest addCommentRequest)
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
                return new HttpUnauthorizedResult("Unauthorized");

            var parentContentGuid = new Guid(addCommentRequest.ParentContentGuid);
            var commentsRepository = ServiceLocator.Resolve<ICommentsRepository>();
            var commentDataMapper = ServiceLocator.Resolve<ICommentDataMapper>();
            var comment = Comment.Create();

            commentsRepository.AddComment(parentContentGuid, commentDataMapper.MapAddCommentRequestToComment(comment, addCommentRequest));

            return new HttpStatusCodeResult(HttpStatusCode.Created);
        }
    }
}
